package com.bocloud.cmp.service.resource;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.dao.CloudVendorDao;
import com.bocloud.cmp.dao.FlavorDao;
import com.bocloud.cmp.driver.providers.intf.FlavorProvider;
import com.bocloud.cmp.entity.resource.CloudVendor;
import com.bocloud.cmp.entity.resource.Flavor;
import com.bocloud.cmp.interfaces.resource.FlavorService;
import com.bocloud.cmp.model.FlavorModel;
import com.bocloud.common.model.BsmResult;
import com.bocloud.common.model.GridBean;
import com.bocloud.common.model.Param;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.GridHelper;
import com.bocloud.common.utils.JSONTools;
import com.bocloud.common.utils.MapTools;
import com.bocloud.coordinator.harmony.HarmonyLock;
import com.bocloud.coordinator.harmony.LockFactory;
import com.google.common.collect.Maps;

/**
 * 配置Service接口实现
 * 
 * @author dongkai
 *
 */
@Service("flavorService")
public class FlavorServiceImpl implements FlavorService {

	private static Logger logger = LoggerFactory.getLogger(ImageServiceImpl.class);
	@Autowired
	private LockFactory lockFactory;
	@Autowired
	private FlavorDao flavorDao;
	@Autowired
	private CloudVendorDao cloudVendorDao;
	@Autowired
	private FlavorProvider flavorProvider;

	@Override
	public BsmResult list(int page, int rows, List<Param> params, Map<String, String> sorter, Boolean simple) {
		try {
			if (null == sorter) {
				sorter = Maps.newHashMap();
			}
			sorter.put("id", Common.ONE);
			List<Flavor> list = flavorDao.list(page, rows, params, sorter);
			for (Flavor flavor : list) {
				CloudVendor cloudVendor = cloudVendorDao.query(flavor.getVendorId());
				if (null != cloudVendor) {
					flavor.setVendorName(cloudVendor.getName());
				}
			}
			int total = flavorDao.count(params);
			GridBean gridBean = GridHelper.getBean(page, rows, total, list);
			return new BsmResult(true, gridBean, "查询成功");
		} catch (Exception e) {
			logger.error("list flavor failure:", e);
			return new BsmResult(false, "查询失败", null, null);
		}
	}

	@Override
	public BsmResult detail(Long id) {
		try {
			Flavor flavor = flavorDao.query(id);
			CloudVendor cloudVendor = cloudVendorDao.query(flavor.getVendorId());
			if (null != cloudVendor) {
				flavor.setVendorName(cloudVendor.getName());
			}
			return new BsmResult(true, flavor, "查询详情成功!");
		} catch (Exception e) {
			logger.error("query flavor detail failure:", e);
			return new BsmResult(false, "查询详情失败!");
		}
	}

	@Override
	public BsmResult listFlavor(Long vendorId, String name) {
		try {
			String[] names = name.split(",");
			List<Flavor> flavors = new ArrayList<>();
			Flavor flavor = null;
			for (String str : names) {
				flavor = flavorDao.getByVid(vendorId, str);
				flavors.add(flavor);
			}
			return new BsmResult(true, flavors, "查询成功!");
		} catch (Exception e) {
			logger.error("list Flavor error:", e);
			return new BsmResult(false, "查询失败!");
		}

	}

	@Override
	public BsmResult create(String params, Long userId) {
		JSONObject object = JSONTools.isJSONObj(params);
		Long id = object.getLong(Common.ID);
		BsmResult result = null;
		try {
			CloudVendor cloudVendor = cloudVendorDao.query(id);
			if (null == cloudVendor) {
				logger.error("get cloudVendor failure!");
				return new BsmResult(false, "创建失败!");
			}
			Map<String, Object> paramMap = MapTools.simpleMap("vendor", cloudVendor.getUuid());
			paramMap.put("params", params);
			FlavorModel model = JSONObject.parseObject(params.toString(), FlavorModel.class);
			Flavor flavorCheck = flavorDao.getByName(model.getName());
			if (null != flavorCheck) {
				return new BsmResult(false, "名称已存在!");
			}
			BsmResult bsmResult = flavorProvider.create(cloudVendor.getUuid(), model);
			if (bsmResult.isFailed()) {
				return new BsmResult(false, bsmResult.getMessage());
			}
			Flavor flavor = JSONObject.parseObject(JSONObject.toJSONString(bsmResult.getData()), Flavor.class);
			flavor.setVendorId(id);
			flavor = flavorDao.save(flavor);
			result = new BsmResult(true, "创建成功!");
		} catch (Exception e) {
			logger.error("create flavor failure:", e);
			return new BsmResult(false, "创建失败!");
		}
		return result;
	}

	@Override
	public BsmResult remove(Long id, Long userId) {
		String path = Flavor.class.getSimpleName() + "_" + id;
		HarmonyLock lock = null;
		Boolean result = false;
		try {
			lock = lockFactory.getLock(path);
			if (!lock.acquire(path, 10, TimeUnit.SECONDS)) {
				logger.warn("Get harmonyLock time out!");
				return new BsmResult(false, "请求超时", "", "");
			}
			Flavor flavor = flavorDao.query(id);
			if (null == flavor) {
				logger.warn("flavor  data not exist");
				return new BsmResult(false, "数据不存在", "", "");
			}
			// 云供应商
			CloudVendor cloudVendor = cloudVendorDao.query(flavor.getVendorId());
			BsmResult bsmResult = flavorProvider.remove(flavor.getFlavorId(), cloudVendor.getUuid());
			if (null == bsmResult || !bsmResult.isSuccess()) {
				return new BsmResult(false, "删除失败");
			}
			result = flavorDao.delete(id);
		} catch (Exception e) {
			logger.error("remove flavor fail:", e);
			return new BsmResult(false, "删除失败", "", "");
		} finally {
			if (null != lock) {
				lock.release();
			}
		}
		return result ? new BsmResult(true, "删除成功") : new BsmResult(false, "删除失败", "", "");
	}

}
